import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { UploadFile } from 'custom';
import { CreateDinnerDto } from './dto/create-dinner.dto';
import { UpdateDinnerDto } from './dto/update-dinner.dto';
import { Dinner } from './entities/dinner.entity';
import { upload } from 'src/utils/qiniu.upload';
import { removeFile } from 'src/utils/qiniu.remove';
const fs = require('fs');
@Injectable()
export class DinnerService {
  constructor(
    @InjectRepository(Dinner)
    private readonly dinnerRepository: Repository<Dinner>,
  ) {}
  //添加餐品
  async create(file: UploadFile, createDinnerDto: CreateDinnerDto) {
    try {
      const result = (await upload(file.path, 'hotel/' + file.filename)) as {
        key: string;
      };
      await fs.unlinkSync(file.path);
      let dinner = new Dinner();
      dinner.name = createDinnerDto.name;
      dinner.price = +createDinnerDto.price;
      dinner.type = +createDinnerDto.type;
      dinner.cover = 'https://wx.tinyxu.fun/' + result.key;
      dinner.key = result.key;
      dinner.soldOut = 0;
      return await this.dinnerRepository.save(dinner);
    } catch (error) {
      throw error;
    }
  }
  //查找所有餐品
  async findAll() {
    return await this.dinnerRepository.find({ order: { id: 'DESC' } });
  }
  //分页查询 
  async findByPage(skip: number, take: number) {
    return await this.dinnerRepository.find({
      order: { id: 'DESC' },
      skip,
      take,
    });
  }
  //查所有条数
  async findCount() {
    return this.dinnerRepository.createQueryBuilder('dinner').getCount();
  }

  //更具分类查找
  async findByType(id: number) {
    return await this.dinnerRepository.find({ where: { type: id } });
  }
  //更新餐品数据
  async update(id: number, updateDinnerDto: UpdateDinnerDto) {
    return await this.dinnerRepository.update(id, updateDinnerDto);
  }
  //更新餐品图片
  async updateCover(file: UploadFile, id: number) {
    try {
      const result = (await upload(file.path, 'hotel/' + file.filename)) as {
        key: string;
      };
      const cover = 'https://wx.tinyxu.fun/' + result.key;
      const key = result.key;
      await fs.unlinkSync(file.path);
      const dinner = (await this.dinnerRepository.find({
        where: { id },
      })) as any;
      await removeFile(dinner.key);
      console.log('*******************');
      return await this.dinnerRepository.update(id, { cover: cover, key: key });
    } catch (error) {
      throw error;
    }
  }
  //删除餐品
  async remove(id: number) {
    return await this.dinnerRepository.delete(id);
  }
}
